import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from '@nestjs/typeorm';
import { FileEntity } from 'src/modules/file/file.entity';
import { UserEntity } from 'src/modules/user/user.entity';
import { ArticleEntity } from 'src/modules/article/article.entity';
import { SMTPEntity } from 'src/modules/smtp/smtp.entity';

@Injectable()
export class DatabaseService implements TypeOrmOptionsFactory {
  private readonly host: string;
  private readonly port: number;
  private readonly dbname: string;
  private readonly username: string;
  private readonly password: string;
  private readonly isDebug: boolean;

  constructor(private readonly configService: ConfigService) {
    this.host = this.configService.get<string>('database.host');
    this.port = this.configService.get<number>('database.port');
    this.dbname = this.configService.get<string>('database.dbname');
    this.username = this.configService.get<string>('database.username');
    this.password = this.configService.get<string>('database.password');
    this.isDebug = this.configService.get<boolean>('app.debug');
  }

  createTypeOrmOptions(): TypeOrmModuleOptions {
    const typeOrmOptions: TypeOrmModuleOptions = {
      type: 'mysql',
      entities: [FileEntity, UserEntity, ArticleEntity, SMTPEntity],
      host: this.host,
      port: this.port,
      username: this.username,
      password: this.password,
      database: this.dbname,
      charset: 'utf8mb4', // 默认字符编码
      timezone: '+08:00', // 时区
      synchronize: true, // 自动创建数据库结构
      logging: this.isDebug ? ['query', 'error'] : false, // 日志等级
      // entityPrefix: 'zu_' // 表前缀
    };

    return typeOrmOptions;
  }
}
